import React from 'react'
import { Table, Icon, Modal, Popconfirm, Form, Input, Row, Col, DatePicker, Button, Message, Select } from 'antd';
const FormItem = Form.Item;
const Option = Select.Option;
import api from '../../../api/adSaleManage';
import EditForm from '../../Form/AdSaleManage';

const { RangePicker } = DatePicker;
import moment from 'moment';

import PanelBox from '../../../components/PanelBox';
import { jsonToTree } from '../../../utils/tools'

import '../../../style/antd-theme.less';

export default class TablePage extends React.Component {
  state = {
    data: [],
    pagination: {
      pageSize: 20,
      pageNum: 1,
    },
    loading: false,
    rowRecord: ''
  };
  columns = [{
    title: '套餐名称',
    dataIndex: 'name',
  },{
    title: '精准/轮播广告单价(1天/1硬件)',
    dataIndex: 'accuratePrice',
    width: '19%',
    render: (text, record) => (
      <span>精准： {record.accuratePrice}(元) / 轮播：{record.turnPrice} (元)</span>
    ),
  }, {
    title: '购买单位(天)',
    dataIndex: 'days',
    width: '10%',
  },{
    title: '联系人',
    dataIndex: 'contacts',
    width: '16%',
    render: (text, record) => (
      <span> {record.contacts}({record.phone})</span>
    ),
  }, {
    title: '开放购买',
    dataIndex: 'allowBuy',
    width: '8%',
    render: (text, record, index) => {
      switch (record.allowBuy) {
        case 1:
          return '是';
        default:
          return '否';
      }
    },
  }, {
    title: '添加日期',
    dataIndex: 'createDate',
    width: '15%',
  }, {
    title: '操作',
    key: 'action',
    width: '10%',
    render: (text, record) => (
      <span>
        <a href="javascript:void(0)" onClick={this.edit.bind(this, record)}>详情</a>
        <span className="ant-divider" />
        <Popconfirm title="您是否要删除该记录?" onConfirm={this.delete.bind(this, record.id)} okText="是" cancelText="否">
          <a href="javascript:void(0)">删除</a>
        </Popconfirm>
      </span>
    ),
  }];

  handleTableChange = (pagination, filters, sorter) => {
    pagination.pageNum=pagination.current;
    this.setState({pagination});
   
    this.fetch({...pagination});
  }
  fetch = (params) => {
    this.setState({ loading: true });
    api.get('/adSaleManage/getAll', { params }).then((data) => {
      const _data = data.data.list;
      const pagination = { ...this.state.pagination };
      pagination.total = data.data.total;
      this.setState({
        loading: false,
        data: _data,
        pagination,
      });
    });
  }

  componentDidMount = () => {
    this.fetch({ ...this.state.pagination });

  }

  add = () => {
    if (this.resetFields) this.resetFields();
    Promise.all([this.getHardList()]).then(([hardList]) => {
      let hardLists=[];
      if(hardList){
        hardList.forEach(function(value) {
          if(value.isInComb != 1){//1被使用
            hardLists.push(value);
          }
        }, this);
      }

      this.setState({
        isOpenModal: true,
        clearForm: false,
        titleName: '创建套餐',
        rowRecord: false,
        hardList:hardLists,
      });
    });
  }
  edit = (record, event) => {
    if (this.resetFields) this.resetFields();
    Promise.all([this.getSaleRowById(record.id), this.getHardList()]).then(([record, hardList]) => {

      let hardLists=[];
      let hards=record.hardIds;
      if(hardList){
        hardList.forEach(function(value) {
          if(hards.indexOf(value.id)!=-1 || value.isInComb != 1){
            hardLists.push(value);
          }
        }, this);
      }
      this.setState({
        isOpenModal: true,
        clearForm: false,
        titleName: '修改套餐',
        rowRecord: record,
        hardList:hardLists,
      })
    });

  }
  getSaleRowById = (id) => {
    return new Promise((resolve, reject) => {
      api.get('/adSaleManage/getAllById', { id: id }).then((data) => {
        resolve(data.data);
      });
    });
  }
  getHardList = () => {
    return new Promise((resolve, reject) => {
      api.get('/hardInfo/getAllByType',{params: {types:14,comb:1}} ).then((data) => {
       
        resolve(data.data);
      });
   });
  } 



  delete = (id, event) => {
    api.delete('/adSaleManage/delete', { id: id }).then((data) => {
      const result = data.data;
      if (result.code == 0) {
        Message.success('删除成功！');
        this.fetch();
      } else {
        Message.error(result.message);
      }
    });
  }

  close = () => {
    this.setState({
      isOpenModal: false,
      clearForm: true,
    });
  }
  refeshData = () => {
    this.fetch({ ...this.state.pagination });
  }

  initChildrenParams = (params) => {
    this.resetFields = params.resetFields;
  }

  render() {

    return (
      <div>
        <SearchForm searchCostState={this.state} goSearch={this.handleTableChange} create={this.add} />
        <PanelBox>
          <Table columns={this.columns} dataSource={this.state.data} pagination={this.state.pagination}
            loading={this.state.loading} onChange={this.handleTableChange} rowKey={'id'}
          />
        </PanelBox>
        <Modal
          title={this.state.titleName}
          visible={this.state.isOpenModal}
          onCancel={this.close}
          width={800}
          wrapClassName="vertical-center-modal"
          footer={null}
        >
          <EditForm hardList={this.state.hardList} rowRecord={this.state.rowRecord} close={this.close} refeshData={this.refeshData} clearForm={this.state.clearForm} callbackParent={this.initChildrenParams} />
        </Modal>
      </div>
    );
  }
}

class SearchsForm extends React.Component {
  // 开始搜索
  goSearch = (e) => {
    let params = this.props.form.getFieldsValue().search;
    let _this = this.props;
    params.pageSize = _this.searchCostState.pagination.pageSize;
    params.pageNum =1;
    params.current =1;
    _this.goSearch(params);

  }

  srearchStyle = {
    labelCol: { span: 8 },
    wrapperCol: { span: 14 },
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { create } = this.props;
    const formItemLayout = this.srearchStyle;
    const search = {
      name: "name",
    };
    return <Form onSubmit={this.goSearch} layout="inline" style={{ marginBottom: '10px' }}>
      <FormItem {...formItemLayout} label="套餐名称" style={{ marginRight: 0, marginBottom: '10px' }}>
        {getFieldDecorator('search.name')(
          <Input type="text" placeholder="请输入套餐名称" />
        )}
      </FormItem>
      <FormItem>
        <Button type="primary" icon="search" htmlType="submit">搜索</Button>
      </FormItem>
      <FormItem>
        <Button type="primary" icon="plus" onClick={create}>添加套餐</Button>
      </FormItem>
    </Form>
  }
}
const SearchForm = Form.create({})(SearchsForm);